﻿using GMS.NET.Core.Entitys.Excel.Basic;
using GMS.NET.Core.Entitys.Excel;
using Microsoft.Extensions.Caching.Memory;
using MiniExcelLibs;

namespace GMS.NET.Core.Tools
{
    /// <summary>
    /// MiniExcel工具扩展
    /// </summary>
    public class MiniExcelTool
    {
        /// <summary>
        /// 根据value获取文件流
        /// </summary>
        /// <param name="values"></param>
        /// <param name="sheetName">第一个sheet名称</param>
        /// <returns></returns>
        public static async Task<MemoryStream> GetExcelStreamAsync(object values,string sheetName="sheet1")
        {
            var memoryStream = new MemoryStream();
             await memoryStream.SaveAsAsync(values,sheetName:sheetName);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return memoryStream;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="memoryStream"></param>
        /// <returns></returns>
        public static   Task<List<Dictionary<string, string>>> GetExcelStreamToDicListAsync(MemoryStream memoryStream)
        {
            var dynamics =  memoryStream.Query(true).Cast<IDictionary<string, object>>();
            //拿到所有的key
            var keysList = dynamics.First().Keys.ToList();
            //拿到所有的表格数据
            var valuesList = dynamics.ToList();
            //创建一个存放结果的容器
            List<Dictionary<string, string>> resultList = new List<Dictionary<string, string>>();
            //遍历结果集
            foreach (var d in valuesList)
            {
                Dictionary<string, string> result = new Dictionary<string, string>();

                foreach (var item in keysList)
                {
                    result.Add(item, d[item] is not null? d[item].ToString()!:"");
                }
                resultList.Add(result);
            }
            return Task.FromResult(resultList);
        }
    }
}
